﻿using BCGM.MedicalWisdom.AuthHelper.OverWrite;
using BCGM.MedicalWisdom.Common.Helper;
using BCGM.MedicalWisdom.Controllers;
using BCGM.MedicalWisdom.IServices;
using BCGM.MedicalWisdom.Model;
using BCGM.MedicalWisdom.Model.Models;
using BCGM.MedicalWisdom.Model.ViewModels.DoctorDTO;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BCGM.MedicalWisdom.Api.Controllers
{
    /// <summary>
    /// 医生列表
    /// </summary>
	[Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize(Permissions.Name)]
    public class DoctorController : BaseApiController
    {
        /// <summary>
        /// 服务器接口，因为是模板生成，所以首字母是大写的，自己可以重构下
        /// </summary>
        private readonly IDoctorServices _doctorServices;
        private readonly IWebHostEnvironment _env;

        public DoctorController(IDoctorServices DoctorServices, IWebHostEnvironment env)
        {
            _doctorServices = DoctorServices;
            _env = env;
        }

        [HttpGet]
        public async Task<MessageModel<PageModel<Doctor>>> Get(int page = 1, string key = "", int intPageSize = 50)
        {
            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }

            Expression<Func<Doctor, bool>> whereExpression = a => true;

            return new MessageModel<PageModel<Doctor>>()
            {
                msg = "获取成功",
                success = true,
                response = await _doctorServices.QueryPage(whereExpression, page, intPageSize)
            };

        }

        [HttpGet("{id}")]
        public async Task<MessageModel<Doctor>> Get(string id)
        {
            return new MessageModel<Doctor>()
            {
                msg = "获取成功",
                success = true,
                response = await _doctorServices.QueryById(id)
            };
        }
        /// <summary>
        /// 注册验证手机号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{phone}")]
        public async Task<MessageModel<Doctor>> GetPhone(string phone)
        {
            var counts = await  _doctorServices.Query(d => d.Phone.Equals(phone));
            if (counts.Count()>0)
            {
                return new MessageModel<Doctor>()
                {
                    msg = "该手机号已注册",
                    success = false,
                };
            }
            return new MessageModel<Doctor>()
            {
                msg = "获取成功",
                success = true,
            };
        }
        /// <summary>
        /// 医生注册
        /// </summary>
        /// <param name="request"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post([FromBody] Doctor request)
        {
            var data = new MessageModel<string>();
            var counts = await _doctorServices.Query(d => d.Phone == request.Phone);
            var password = request.Password;
            if (counts.Count() > 0)
            {
                return Failed("该手机号已经注册");
            }
            if (password.Length<8)
            {
                return Failed("密码不得小于8位");
            }
            request.Password = MD5Helper.MD5Encrypt16(request.Password);
            var id = await _doctorServices.Add(request);
            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }

            return data;
        }
        /// <summary>
        /// 上传图片,多文件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        // [Route("/images/Upload/Pic")]
        public async Task<MessageModel<string>> InsertPicture([FromForm] DcotorPhotoDTO dto)
        {
            var data = new MessageModel<string>();
            //医生照片非空
            if (dto.DoctorFile == null || !dto.DoctorFile.Any()) return Failed("请选择上传的文件。");
            //格式限制
            var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" };

            var allowedFile = dto.DoctorFile.Where(c => allowType.Contains(c.ContentType));
            if (!allowedFile.Any()) return Failed("图片格式错误");
            if (allowedFile.Sum(c => c.Length) > 1024 * 1024 * 4) return Failed("图片过大");

            string foldername = "images";
            string folderpath = Path.Combine(_env.WebRootPath, foldername);
            if (!Directory.Exists(folderpath))
            {
                Directory.CreateDirectory(folderpath);
            }
            foreach (var file in allowedFile)
            {
                string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + Path.GetFileName(file.FileName));
                var path = Path.Combine(_env.WebRootPath, strpath);

                using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(stream);
                }
            }

            var excludeFiles = dto.DoctorFile.Except(allowedFile);

            if (excludeFiles.Any())
            {
                var infoMsg = $"{string.Join('、', excludeFiles.Select(c => c.FileName))} 图片格式错误";
                return Success<string>(null, infoMsg);
            }

            return Success<string>(null, "上传成功");

        }

        //[HttpPut]
        //public async Task<MessageModel<string>> Put([FromBody] Doctor request)
        //{
        //    var data = new MessageModel<string>();
        //    data.success = await _doctorServices.Update(request);
        //    if (data.success)
        //    {
        //        data.msg = "更新成功";
        //        data.response = request?.id.ObjToString();
        //    }

        //    return data;
        //}
        /// <summary>
        /// 医生删除  逻辑单删
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id)
        {
            var data = new MessageModel<string>();
            var model = await _doctorServices.QueryById(id);
            model.Isdel = 1;
            data.success = await _doctorServices.Update(model);
            if (data.success)
            {
                data.msg = "删除成功";
                data.response = model?.Id.ObjToString();
            }

            return data;
        }
        /// <summary>
        /// 医生管理+医名查询
        /// </summary>
        /// <param name="DoctorName"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<DoctorDTOs>>> DoctorList(string DoctorName)
        {
            return new MessageModel<List<DoctorDTOs>> ()
            {
                msg = "获取成功",
                success = true,
                response = await _doctorServices.GetBlogs(DoctorName)
            };

        }
        /// <summary>
        /// 获取JWT的方法1
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Token")]
        public async Task<MessageModel<string>> GetJwtStr(DoctorLoginDTO list)//异步接口，可以提高接口的并发量
        {

            string jwtStr = string.Empty;
            bool suc = false;
            //这里就是用户登陆以后，通过数据库去调取数据，分配权限的操作

            var user = await _doctorServices.DoctorLogin(list);//MD5Helper帮助类：加密密码
            if (user != null)
            {

                TokenModelJwt tokenModel = new TokenModelJwt { Uid = 1, Role = user };

                jwtStr = JwtHelper.IssueJwt(tokenModel);
                suc = true;
            }
            else
            {
                jwtStr = "login fail!!!";
            }

            return new MessageModel<string>()
            {
                success = suc,
                msg = suc ? "获取成功" : "获取失败",
                response = jwtStr
            };
        }
    }
}